package com.lxh.cptp.controller;

import com.alibaba.fastjson.JSONObject;
import com.lxh.cptp.config.WxCpTpConfiguration;
import com.lxh.cptp.utils.JsonUtils;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.util.RandomUtils;
import me.chanjar.weixin.common.util.crypto.SHA1;
import me.chanjar.weixin.cp.api.WxCpTpService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

import static com.lxh.cptp.config.WxCpTpConfiguration.SUIT_ID;

/**
 * created by lanxinghua@2dfire.com on 2020/2/23
 * 授权相关(第三方应用)
 */
@RestController
@RequestMapping("/wx/oauth")
public class WxCpTpOauthController extends BaseController{
    private WxCpTpService tpService;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private String oauthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_privateinfo&state=%s#wechat_redirect";
    private String loginUrl = "http://chenxingxing.51vip.biz/wx/oauth/login";


    /**
     * 拆分链接
     * @param url
     */
    @GetMapping("/jump")
    public void jump(String url,
                     HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(url)) {
            throw new IllegalArgumentException("url is empty");
        }
        oauthUrl = String.format(oauthUrl, SUIT_ID, loginUrl, url);
        logger.info("跳转url:" + oauthUrl);
        response.sendRedirect(oauthUrl);
    }


    /**
     * 授权链接  通过code换取用户信息
     */
    @GetMapping("/login")
    public void login(String code,
                      String state,
                      HttpServletRequest request,
                      HttpServletResponse response) {
        if (StringUtils.isBlank(code)) {
            throw new IllegalArgumentException("code is empty");
        }
        try {
            tpService = WxCpTpConfiguration.getCpTpService(SUIT_ID);
            JSONObject userInfo3rd = getUserInfo3rd(tpService, code);
            if (userInfo3rd == null){
                throw new Exception("用户信息获取失败");
            }
            JSONObject userInfoDetail = getUserDetail3rd(tpService, userInfo3rd.get("user_ticket").toString());
            request.getSession().setAttribute("token", userInfoDetail);
            response.sendRedirect(state);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }
    }


    /**
     * 创建js-sdk签名
     * @param url
     * @return
     * @throws Exception
     */
    @RequestMapping("/create/jsapi_sign")
    @ResponseBody
    public Object jssdk(@RequestParam  String url,
                        HttpServletRequest request) throws Exception{
        // 从url里面解析test参数
        String auth_corpId = "wwd276de90ff82e1e3";
        if (url.contains("entityId")){
            Map<String, Object> parameter = getParameter(url);
            auth_corpId = testMap.get(parameter.get("entityId").toString());
        }
        if (StringUtils.isEmpty(auth_corpId)){
            throw new Exception("企业授权id为空.");
        }
        logger.info("authCorpId:{}  url:{}", auth_corpId, url);
        tpService = WxCpTpConfiguration.getCpTpService(SUIT_ID);
        long timestamp = System.currentTimeMillis() / 1000;
        String nonceStr = RandomUtils.getRandomStr();
        JSONObject object = getJsApiTicket(auth_corpId, tpService);
        String jsApiTicket = object.getString("ticket");
        String signature = SHA1.genWithAmple(
                "jsapi_ticket=" + jsApiTicket,
                "noncestr=" + nonceStr,
                "timestamp=" + timestamp,
                "url=" + url
        );
        WxJsapiSignature jsapiSignature = new WxJsapiSignature();
        jsapiSignature.setTimestamp(timestamp);
        jsapiSignature.setNonceStr(nonceStr);
        jsapiSignature.setUrl(url);
        jsapiSignature.setSignature(signature);
        jsapiSignature.setAppId(auth_corpId);
        logger.info("data：" + JsonUtils.toJson(jsapiSignature));
        return jsapiSignature;
    }
}
